package com;

import static org.openqa.selenium.support.ui.ExpectedConditions.*;
import static org.junit.Assert.*;
import org.junit.*;
import org.openqa.selenium.*;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
import pages.InternalPage;
import pages.LoginPage;

public class TestLoginLogout extends TestBase {

	private WebDriverWait wait;
	private LoginPage loginPage;
	private InternalPage internalPage;

	@Test
	public void testLoginLogOut() throws Exception {
		goToMainPage("http://localhost/php4dvd/");
		if (isLoggedIn()) {
			logOut();
		}
		assertTrue("Не найдено поле ввода логина",
				loginPage.checkUserNameFieldExist());
		loginTest("admin", "admin");
		assertTrue("Не найден один из элементов главной страницы",
				internalPage.isOnMainPage());
		assertkHeadLinksExist("My profile");
		logOut();
		assertTrue("Не найдено поле ввода логина",
				loginPage.checkUserNameFieldExist());
		loginTest("-", "-");
		assertWrongPasswordError();
	}

	public boolean isLoggedIn() {
		return driver.findElements(By.linkText("My profile")).size() > 0;
	}

	private void assertWrongPasswordError() {
		assertEquals("Incorrect user name or password",
				loginPage.IncorrectUserNameOrPasswordString.getText());
	}

	private void logOut() {
		internalPage.menuLogOutLink.click();
		confirmIsPresent().accept();
	}

	private void assertkHeadLinksExist(String linkString) {
		assertEquals(linkString,
				wait.until(visibilityOfElementLocated(By.linkText(linkString)))
						.getText());
	}

	private void loginTest(String userName, String password) {
		loginPage.userNameFieldOnLoginPage.clear();
		loginPage.userNameFieldOnLoginPage.sendKeys(userName);
		loginPage.passwordField.clear();
		loginPage.passwordField.sendKeys(password);
		loginPage.loginButton.click();
	}

	private void goToMainPage(String baseUrl) {
		driver.get(baseUrl);
		
		loginPage = PageFactory.initElements(driver, LoginPage.class);
		internalPage = PageFactory.initElements(driver, InternalPage.class);
	}

}
